/*
 * @Author: Wangjun
 * @Date: 2023-03-15 13:32:52
 * @LastEditTime: 2024-11-06 12:36:47
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \golib\js\jsutil\model.go
 * hnxr
 */
package jsutil

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/easy"
	"github.com/dop251/goja"
)

// YYYY/MM/DD HH:mm:ss
// 初始化js需要的组件
func InitModels(vm *goja.Runtime) {
	//注册console组件
	stacks := make([]goja.StackFrame, 2)
	console := vm.NewObject()
	stack := func() string {
		ss := vm.CaptureCallStack(2, stacks)
		i := len(ss) - 1
		if i < 0 {
			return ""
		}
		pos := ss[i].Position()
		funcName := ss[i].FuncName()
		if pos.Line > 0 {
			if pos.Filename != "" {
				if funcName != "" {
					return fmt.Sprintf("%s:%d [%s] ", pos.Filename, pos.Line, funcName)
				}
				return fmt.Sprintf("%s:%d ", pos.Filename, pos.Line)
			}
			if funcName != "" {
				if funcName == "<anonymous>" {
					return fmt.Sprintf("main.js:%d  ", pos.Line)
				}
				return fmt.Sprintf("main.js:%d [%s] ", pos.Line, funcName)
			}
			return fmt.Sprintf("main.js:%d ", pos.Line)
		}
		return ""
	}
	console.Set("log", func(v ...interface{}) {
		logs.LiteInfo(stack(), v...)
	})
	console.Set("info", func(v ...interface{}) {
		logs.LiteInfo(stack(), v...)
	})
	console.Set("warn", func(v ...interface{}) {
		logs.LiteWarn(stack(), v...)
	})
	console.Set("error", func(v ...interface{}) {
		logs.LiteError(stack(), v...)
	})
	vm.Set("console", console)

	vm.Set("load", func(name string) goja.Value {
		data, err := os.ReadFile(GetJsDir() + name)
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		_, err = vm.RunScript(name, string(data))
		if err != nil {
			vm.Interrupt(err)
			return nil
		}

		return vm.Get("model")
	})

	vm.Set("loadjs", func(name string) goja.Value {
		data, err := os.ReadFile(GetJsDir() + name)
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		_, err = vm.RunScript(name, string(data))
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		name = filepath.Base(name)
		ext := filepath.Ext(name)
		if ext != "" {
			name = strings.TrimSuffix(name, ext)
		}

		return vm.Get(name)
	})

	//注册加载库 = loadjs
	vm.Set("require", func(name string) goja.Value {
		data, err := os.ReadFile(GetJsDir() + name)
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		_, err = vm.RunScript(name, string(data))
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		name = filepath.Base(name)
		ext := filepath.Ext(name)
		if ext != "" {
			name = strings.TrimSuffix(name, ext)
		}

		return vm.Get(name)
	})

	//2006-01-02 15:04:05.999
	//注册时间组件, 后续进行优化
	fecha := vm.NewObject()
	fecha.Set("format", func(x time.Time, fmt string) string {
		return x.Format(easy.ConvertFormat(fmt))
	})

	vm.Set("dayjs", fecha)
	vm.Set("fecha", fecha)
}
